package com.lishem.carl._01array;

/**
 * https://leetcode.cn/problems/binary-search/description/
 * <p>
 * 给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target
 * <p>
 * 写一个函数搜索 nums 中的 target，如果目标值存在返回下标，否则返回 -1。
 * <p>
 * 示例 1：
 * <p>
 * nums = [-1,0,3,5,9,12], target = 9
 * <p>
 * 输出4   9 的下标为4
 * <p>
 * 示例2：
 * <p>
 * nums = [-1,0,3,5,9,12], target = 2
 * <p>
 * 输出: -1   2 不存在 nums 中因此返回 -1
 */
public class _1LetCode704_二分查找 {

    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }


    public static void main(String[] args) {
        _1LetCode704_二分查找 sol = new _1LetCode704_二分查找();
        System.out.println(sol.search(new int[]{5}, 5));
        System.out.println(sol.search(new int[]{-1, 0, 3, 5, 9, 12}, 9));
        System.out.println(sol.search(new int[]{-1, 0, 3, 5, 9, 12}, 2));
    }
}
